# -*- coding: utf-8 -*-

"""
工具库：SUMMARY.md 相关
"""

import codecs
import os
import re
import shutil
import time


def parse(filepath, parent=''):
    """ 解析 SUMMARY.md """
    re_chapter = re.compile(r'(?P<spaces> +)?\* \[(?P<title>[^\]]+)\]\((?P<path>[^\)]+)\)', re.U)
    with codecs.open(filepath, 'r', 'utf-8') as _file:
        lines = [line for line in _file.read().split('\n')]
    chapters = [re_chapter.search(line) for line in lines]
    chapters = [i.groupdict() for i in chapters if i]
    for chapter in chapters:
        # chapter['level'] = int(math.ceil(len(chapter['spaces']) / 4.0)) if chapter['spaces'] else 0
        # if parent:
        #     chapter['level'] += parent.count('/') + 1
        chapter['path'] = ((parent + '/') or '') + chapter['path']
        chapter['spaces'] = chapter['spaces'] or ''
        chapter['level'] = chapter['path'].count('/') + int(not chapter['path'].endswith('README.md')) - 1
    return chapters


def show(chapters):
    """ 显示章节 """
    if isinstance(chapters, str):
        chapters = parse(chapters)
    for chapter in chapters:
        if chapter['level']:
            print u'   ' + (u'    ' * (chapter['level'] - 1)) + u'--- ' + chapter['title']
        else:
            # print u'★ ' + chapter['title']
            print '** ' + chapter['title']


def show_book(book_name, base_name):
    """ show book """
    print (u'【 %s 】' % book_name).center(70, '*')
    print
    show(os.path.join(base_name, book_name, 'SUMMARY.md'))
    print


def write(chapters, target_dir):
    """ 写 SUMMARY.md """

    def chapter_fmt(chapter):
        """ 格式化 """
        spaces = (u'    ' * chapter['level']) if chapter['level'] else ''
        return '%s* [%s](%s)' % (spaces, chapter['title'], chapter['path'])

    lines = [chapter_fmt(chapter) for chapter in chapters]
    lines.insert(0, '# SUMMARY\n')

    backup_path = os.path.join(target_dir, 'bak.%d.SUMMARY.md' % time.time())
    shutil.copyfile(os.path.join(target_dir, 'SUMMARY.md'), backup_path)

    with codecs.open(os.path.join(target_dir, 'SUMMARY.md'), 'w', 'utf-8') as _file:
        _file.write('\n'.join(lines))
